[8] 進階資料型別 part3 - Set、Dict


Posted by bessyhuang on 2023-06-03

Set 集合

為何需要 Set?

簡介

  • 由一連串資料所組成,包含沒有順序沒有重複可改變內容(mutable)的多個資料。
    • 概念上,等同於 數學的集合(set)
    • set 中,每次出現的元素順序不一定相同。
  • { } 大括號 標示,裡面的資料以逗號 , 隔開。
  • set 中可以包含不同型別的元素。
      test1 = {1, "Taipei", 2, "Tokyo"}
    
  • 若 set 的元素相同但順序不同,仍是相同 set。

      test1 = {1, "Taipei", 2, "Tokyo"}
      test2 = {2, 1, "Taipei", "Tokyo"}
    
      print(test1 == test2)
      # True
    

建立集合

  • 空集合
      # 使用 Python 內建的 set() 函式建立集合,唯一方法!
      set1 = set()
    
  • 包含數值或文字的集合

      # 方法一
      set2 = set([1, 2, 3])
    
      # 方法二
      set3 = {1, 2, 2, 3, 4}
      # {1, 2, 3, 4}
    
      # 方法三:將 list, tuple 直接轉換為 set
      set4 = set(["A", "B", "C", "D"])
      set4 = set(("A", "B", "C", "D"))
    
  • 從 range 建立集合

      # 方法一
      set5 = set(range(5))
    
      # 方法二:串列解析法 (List comprehension)
      set5 = set([i for i in range(5)])
    
      # ERROR: 'set' object has no attribute 'append'
      set5 = set()
      for i in range(5):
          set5.append(i)
    

內建函式

💡 原則上,不涉及 與順序相關的運算 均適用於 set。

  • 適用
    • len(S)max(S)min(S)sum(S)
  • 不適用
    • .index(x).count(x)
    • random 模組的 shuffle(L):將 L 中的元素隨機重排。(涉及變更元素的順序,而集合中的元素無順序之分)

運算子

  • 適用
    • 比較運算子: > < >= <= == !=
        💡 set 中的比較運算子,意義有些不同。
      
      • S1 == S2:若 S1 和 S2 包含完全相同的元素,return True
      • S1 <= S2:若 S1 是 S2 的子集合(subset),return True
      • S1 < S2:若 S1 是 S2 的真子集合(proper subset),return True
    • in not in 運算子
        print("ab" in {2, "abc", "ba"})
        # False
      
  • 不適用
    • 連接運算子+、重複運算子*
    • Index 與 Slicing

比較運算子

  • S1 == S2

    • 若 S1 和 S2 包含完全相同的元素,return True

        a = {1, 2, 3}
        b = {1, 2, 3, 4, 5}
      
        print(a == b)
        # False
      
  • S1 <= S2

    • 若 S1 是 S2 的子集合(subset),return True
    • 存在於 S1 (e.g. a) 的每個元素亦存在於 S2 (e.g. b)。

        a = {1, 2, 3}               # a 為 b 的子集合,存在於 a 的每個元素亦存在於 b
        b = {1, 2, 3, 4, 5}         # b 為 a 的超集合
      
        print(a <= b)
        # True
      
  • S1 < S2

    • 若 S1 是 S2 的真子集合(proper subset),return True
    • 存在於 S1 (e.g. a) 的每個元素亦存在於 S2 (e.g. b),且 S2 (e.g. b) 至少有一個元素不存在於 S1 (e.g. a)。

        a = {1, 2, 3}               # a 為 b 的子集合,存在於 a 的每個元素亦存在於 b
        b = {1, 2, 3}
      
        print(a < b)
        #False
      
        a = {1, 2, 3}               # a 為 b 的子集合,存在於 a 的每個元素亦存在於 b
        b = {1, 2, 3, 4, 5}         # b 為 a 的超集合
      
        print(a < b)
        # True
      
  • Set 練習題

      a = {"a", "b", "c"}
      b = {"a", "b", "c", "d"}
      c = {"a", "b", "c"}
      d = {"a",      "c",     "e"}
      e = {"a",      "c",     "e", "f"}
    
      print(a == c)     # True
      print(a != b)     # True
      print(a <= b)     # True
      print(a < b)      # True
      print(c >= d)     # False
      print(c > d)      # False
      print(e > d)      # True
    

集合處理方法

💡 符號表示之說明
     - x  單一的元素
     - S  集合 (set)
     - i  索引值
  • 適用

    • 新增 / 複製:S.add(x)S.copy()
    • 刪除:S.remove(x)S.clear()S.pop()del 刪除 變數本身

        💡 pop 隨機移除一個元素,並 return 該元素的值。(for set)
        💡 pop 移除特定索引的元素,並 return 該元素的值。(for list:list.pop([index=-1]))
      
        💡 del 只可用來刪除變數本身,而不可刪除 set 裡的元素。
      
    • 排序

      • sorted(T)

          💡 S.sort() 對原始 set 的元素排序,未創建新的 set。
             => 出現 Error!
        
          💡 sorted(S) 對由 set 新產生的 list 元素排序,不改變原始 set。
        
          S = {1, 0, 3, 4, 2, -1, 1.5, 5}
          S.sort()
          # ERROR: 'set' object has no attribute 'sort'
        
          S1 = {1, 0, 3, 4, 2, -1, 1.5, 5}
          print(sorted(S1))
          # [-1, 0, 1, 1.5, 2, 3, 4, 5]
          print(S1)
          # {0, 1, 2, 3, 4, 1.5, 5, -1}
        
  • 不適用
    • list.sort(reverse=False)list.reverse()
    • list.append(x)list.extend(L)list.insert(i, x)list.pop([i])
    • del:用來從 list 中 刪除 指定索引 的元素。

Dict 字典

為何需要 Dict?

簡介

  • 包含沒有順序沒有重複可改變內容(mutable)的多個『 鍵:值對(key:value pair)』。

    • 一種對映型別。
    • key

      • 不能重複,因為是透過 key 來取得、新增、變更或刪除對應的值。
      • 只能是數值、字串或 tuple 等 不可改變內容 的資料。

          test1 = {1: "Taipei", 2: "Tokyo", [1, 2]: "sheep"}
          # TypeError: unhashable type: 'list'
        
          test2 = {1: "Taipei", 2: "Tokyo", (1, 2): "sheep"}
        
    • value
      • 無限制,如:value 可重複。
          test1 = {1: "Taipei", 2: "Tokyo", 3: "Taipei"}
        
  • { } 大括號 標示,裡面的『 鍵:值對(key:value pair)』以逗號 , 隔開。
  • 鍵:值對 (key: value pair) 相同但順序不同,仍是相同 dict。

      test1 = {1: "Taipei", 2: "Tokyo", "stud_a": "丰嘉", "stud_b": "夜貓", "stud_c": "許羊"}
      test2 = {"stud_a": "丰嘉", 2: "Tokyo", "stud_c": "許羊", 1: "Taipei", "stud_b": "夜貓"}
    
      print(test1 == test2)
      # True
    

建立字典

  • 空字典

      # 方法一:使用 Python 內建的 dict() 函式建立串列
      dict1 = dict()
    
      # 方法二
      dict1 = {}
    
  • 包含『鍵:值對(key:value pair)』的字典

      # 方法一
      dict_A = dict({"three": 3, "one": 1, "two":2})
    
      # 方法二
      dict_B = {"three": 3, "one": 1, "two":2}
    
      # 方法三
      dict_C = dict(three = 3, one = 1, two = 2)
    
      print(dict_A == dict_B == dict_C)
      # True
    

字典的基本操作:取得、增修、刪除

  • 取得『鍵:值對(key:value pair)』
      A = {"three": 3, "one": 1, "two":2}
      print(A['one'])
      # 1
    
  • 新增或變更『鍵:值對(key:value pair)』
      語法:
      dict_name[key] = value
    
      A = {"three": 3, "one": 1, "two":2}
      A['four'] = 4      #新增
      A['four'] = "四"   #修改
    
  • 刪除『鍵:值對(key:value pair)』
      語法:
      del dict_name[key]
    
      A = {"three": 3, "one": 1, "two":2}
      del A['one']       #刪除
    

內建函式

💡 原則上,不涉及 與順序相關的運算 均適用於 dict。

💡 符號表示之說明
     - x  單一的元素
     - D  字典 (dict)
     - i  索引值
  • 適用
    • len(D):計算總共多少 key: value pair
  • 不適用
    • max(S)min(S)sum(S)
    • .index(x).count(x)
    • random 模組的 shuffle(L):將 L 中的元素隨機重排。(涉及變更元素的順序,而字典中的元素無順序之分)

運算子

  • 適用

    • in not in 運算子

        print("one" in {"three": 3, "one": 1, "two":2})               
        # True
      
        print(1 in {"three": 3, "one": 1, "two":2})                   
        # False
      
    • 比較運算子: == !=
  • 不適用
    • 連接運算子+、重複運算子*
    • 比較運算子: > < >= <=
    • Index 與 Slicing

字典處理方法

字典處理方法(使用內建函式)


References

補充

  1. frozenset() 用於建立 不可改變內容 的集合
  2. 集合的數學運算:交集、聯集、差集

#Python #set #Dict







Related Posts

Longformer - The Long-Document Transformer

Longformer - The Long-Document Transformer

Jest 自己的程式自己測試

Jest 自己的程式自己測試

The introduction and difference between class component and function component in React

The introduction and difference between class component and function component in React


Comments